document.addEventListener('DOMContentLoaded', function() {
    const registerForm = document.getElementById('register-form');
    registerForm.addEventListener('submit', function(event) {
        event.preventDefault();
        const username = document.getElementById('reg-username').value;
        const password = document.getElementById('reg-password').value;
        const email = document.getElementById('reg-email').value;
        const sex = document.getElementById('reg-sex').value;

        registerUser(username, password, email, sex);
    });
});

function registerUser(username, password, email, sex) {
    fetch('/blog/user/register', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password, email, sex })
    })
        .then(response => response.json())
        .then(data => {
            if (data.code === 1) {
                document.getElementById('register-response').innerHTML = `
                <p>注册成功：${data.data}</p>
            `;
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 2000); // 2秒后跳转到登录页面
            } else {
                document.getElementById('register-response').innerHTML = `
                <p>注册失败：${data.msg}</p>
            `;
            }
        })
        .catch(error => {
            document.getElementById('register-response').innerHTML = `
            <p>请求失败：${error.message}</p>
        `;
        });
}
